<template>
  <div>
    <a-button type="primary" style="margin-top: 20px" @click="showModal">
      <a-icon type="plus" />
      根据源单生成
    </a-button>

    <a-modal
      title="生产材料单生成退库申请单"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      width="70%"
    >
      <!-- 搜索表单---查询条件 -->
      <a-form v-bind="layout">
        <a-row>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-item label="申请日期">
              <a-range-picker
                v-model="searchForm.rangeDate"
                @change="getRangeTime"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-item label="单据状态">
              <a-select v-model="searchForm.documentClosed" style="width: 100%">
                <a-select-option
                  v-for="item in documentClosedList"
                  :key="item"
                  :value="item"
                >
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!-- <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24"></a-col> -->
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-item label="单据号">
              <a-select
                v-model="searchForm.document"
                style="width: 100%"
                showSearch
              >
                <a-select-option
                  v-for="(item, index) in OrderList"
                  :key="index"
                  :value="item"
                >
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-item label="所属分厂">
              <a-tree-select
                v-model="searchForm.ownedBranch_text"
                style="width: 100%"
                :tree-data="ownedBranchList"
                showSearch
                @change="changeOwnedBranchTreeNode"
              >
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-model-item label="产成品分类" prop="finishGoodsType">
              <a-tree-select
                showSearch
                v-model="searchForm.finishedProductType_dictText"
                @change="setFinishGoodsType"
                :tree-data="finishGoodsTypeList"
                style="width: 100%"
              >
              </a-tree-select>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-model-item
              label="产成品仓库"
              prop="finishedProductDepot_dictText"
            >
              <a-select
                v-model="searchForm.finishedProductDepot_dictText"
                showSearch
                style="width: 100%"
                @change="finishedProductDepotChange"
              >
                <a-select-option
                  v-for="item in finishedProductDepotList"
                  :key="item.finishedProductDepot"
                  :value="
                    item.finishedProductDepot +
                    '|' +
                    item.finishedProductDepotNo +
                    '|' +
                    item.finishedProductDepot_dictText
                  "
                  >{{ item.finishedProductDepotNo }}
                  {{ item.finishedProductDepot_dictText }}</a-select-option
                >
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24"></a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24"></a-col>
          <!-- 按钮 -->
          <a-col
            :xl="8"
            :lg="8"
            :md="8"
            :sm="24"
            :xs="24"
            :style="{ textAlign: 'right' }"
            ><div style="margin-top: 10px">
              <a-button type="primary" @click="Search()">查询</a-button>
              <a-button style="margin-left: 8px" @click="Reset()"
                >重置</a-button
              >
            </div>
          </a-col>
        </a-row>
      </a-form>

      <a-divider />

      <!-- 备货通知单、销售订单等单据 -->
      <a-table
        style="margin-top: 20px"
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        @change="handleTableChange"
        :row-selection="{
          selectedRowKeys: orderSelectedRowKeys,
          onChange: orderSelectChange,
          type: 'radio',
          getCheckboxProps: getCheckboxProps,
        }"
      >
        <!-- 审核标志 -->
        <span slot="documentClosed" slot-scope="text, record">
          <a-popconfirm
            title="是否关闭单据?"
            v-if="record.documentClosed == '开启'"
            @confirm="Giorto(record, 1)"
          >
            <a> {{ text }} </a>
          </a-popconfirm>
          <a-popconfirm
            title="是否开启单据?"
            v-if="record.documentClosed == '关闭'"
            @confirm="Giorto(record, 1)"
          >
            <a> {{ text }} </a>
          </a-popconfirm>
        </span>
      </a-table>

      <a-divider />
      <!-- 单据中的物品 -->
      <a-table
        style="margin-top: 10px"
        :columns="listColumns"
        :data-source="listDataSource"
        :scroll="{ x: 1500 }"
        :row-selection="{
          selectedRowKeys: listSelectedRowKeys,
          onChange: listOnSelectChange,
          getCheckboxProps: getCheckboxProps,
        }"
      >
        <!-- 审核标志 -->
        <span slot="documentClosed" slot-scope="text, record">
          <a-popconfirm
            title="是否关闭单据?"
            v-if="record.documentClosed == '开启'"
            @confirm="Giorto(record, 2)"
          >
            <a> {{ text }} </a>
          </a-popconfirm>
          <a-popconfirm
            title="是否开启单据?"
            v-if="record.documentClosed == '关闭'"
            @confirm="Giorto(record, 2)"
          >
            <a> {{ text }} </a>
          </a-popconfirm>
        </span>
      </a-table>

      <!-- 备货通知单物品信息 -->
    </a-modal>
  </div>
</template>

<script>
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口

const columns = [
  // {
  //   title: "序号",
  //   dataIndex: "key",
  //   key: "key",
  //   align: "center",
  //   width: "80px",
  // },
  {
    title: "单据号",
    dataIndex: "document",
    key: "document",
    align: "center",
  },
  {
    title: "所属分厂",
    dataIndex: "ownedBranch_dictText",
    key: "ownedBranch_dictText",
    align: "center",
  },
  {
    title: "单据日期",
    dataIndex: "documentDate",
    key: "documentDate",
    align: "center",
  },
  {
    title: "产成品分类",
    dataIndex: "finishedProductType_dictText",
    key: "finishedProductType_dictText",
    align: "center",
  },
  {
    title: "产成品仓库",
    dataIndex: "finishedProductDepot_dictText",
    key: "finishedProductDepot_dictText",
    align: "center",
  },
  {
    title: "单据状态",
    dataIndex: "documentClosed",
    align: "center",
    scopedSlots: { customRender: "documentClosed" },
  },
];

const listColumns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
    width: "80px",
  },

  {
    title: "仓库名称",
    key: "depotId_dictText",
    dataIndex: "depotId_dictText",
    align: "center",
  },
  {
    title: "存货编码",
    dataIndex: "invcode",
    key: "invcode",
    align: "center",
    width: "200px",
  },
  {
    title: "存货名称",
    dataIndex: "invname",
    key: "invname",
    align: "center",
  },
  {
    title: "规格型号",
    dataIndex: "invspec",
    key: "invspec",
    align: "center",
  },
  {
    title: "单位",
    key: "measname",
    dataIndex: "measname",
    align: "center",
  },

  {
    title: "入库数量",
    dataIndex: "quantity",
    key: "quantity",
    align: "center",
  },

  {
    title: "单价",
    key: "unitPrice",
    dataIndex: "unitPrice",
    align: "center",
  },
  {
    title: "金额",
    key: "money",
    dataIndex: "money",
    align: "center",
  },
  {
    title: "出菇领料金额",
    key: "amountOfFruitPicking",
    dataIndex: "amountOfFruitPicking",
    align: "center",
  },
  {
    title: "备注",
    key: "remark",
    dataIndex: "remark",
    align: "center",
  },
  {
    title: "单据状态",
    dataIndex: "documentClosed",
    align: "center",
    scopedSlots: { customRender: "documentClosed" },
  },
];

export default {
  data() {
    return {
      finishGoodsTypeList: [], //产成品分类列表
      finishedProductDepotList: [], //产成品仓库

      savefenchang: "",
      ownedBranchList: [], //所属分厂列表
      OrderList: [],
      visible: false,
      documentClosedList: ["开启", "关闭"],
      saveid: "",
      savedocumentClosed: "",
      searchForm: {
        ownedBranch_text: "",
        document: "",
        salesDepartment: "", // 销售部门
        deptId: "", // 销售部门Id
        rangeDate: null, // 日期范围
        documentClosed: "开启",
        startTime: "", // 开始日期
        endTime: "", // 结束日期
      },
      saleDepartmentList: [], // 销售部门
      ClientList: [], // 客户列表

      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 15 },
      },

      columns,
      dataSource: [],
      orderSelectedRowKeys: [],

      listColumns,
      listDataSource: [],
      listSelectedRowKeys: [], // 列表选择

      pagination: {
        total: 0,
        current: 1,
        pageSize: 5, //每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ["5"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
      },
      queryParam: {
        //查询参数
        page: 1, //第几页
        size: 5, //每页中显示数据的条数
        hosName: "",
        hosCode: "",
        province: "",
        city: "",
      },

      Form: {
        requisitionNo: "", // 订单号
        applicationDept: "", // 销售部门
        applicationDeptId: "", // 销售部门Id
        clientId: "", // 客户
        client: "", // 客户名称
        goodsList: [], // 物品列表
      },
    };
  },
  mounted() {
    this.getSaleDepartmentList();
    this.getOrderList();
    this.getownedBranchTree(); //获取分厂列表
    this.getFinishGoodsTypeList(); //获取产成品分类列表
    this.getfinishedProductDepot(); //产成品仓库
  },
  methods: {
    /**
     //todo 审核标志-单据关闭功能 
     * @description: 审核标志-单据关闭功能
     * @description: 
     * @return
     */
    Giorto(record, select) {
      let that = this;
      console.log(`选中了${select}表格信息`);
      console.log(`选中该记录返回的所有信息:`, record);
      //路线判断
      record.documentClosed === "开启"
        ? goState.call(that, "关闭", record)
        : goState.call(that, "开启", record);

      function goState(status, record) {
        console.log(`正在执行状态${status}功能:::::::::`);
        let data = {
          id: record.id,
          documentClosed: status,
          objectInformationId: record.objectInformationId,
        };
        //接口判断
        return select === 1
          ? this.updatePurchaseaAddorder(data, status)
          : this.updatePurchaseiItemiInformation(data, status);
      }
    },
    //接口关闭-上A
    updatePurchaseaAddorder(data, status) {
      console.log(111);
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        if (!res.success) {
          this.$message.error(res.message);
          return;
        }
        this.$message.success(`${status}成功!`);
        console.log(`Success::::::${status}功能成功执行`);
        this.getArrayListByOriginDocument(); //获取采购订单列表
      });
    },
    //接口关闭-下
    updatePurchaseiItemiInformation(data) {
      let message = {
        id: this.saveid,
        documentClosed: this.savedocumentClosed,
        warehouseObjectInformationEntities: [
          {
            documentClosed: data.documentClosed,
            id: data.objectInformationId,
          },
        ],
      };
      comHttp.updateInOrOutStorageOrderAndGoods(message).then((res) => {
        if (!res.success) {
          this.$message.error(res.message);
          return;
        }
        this.$message.success(`${status}成功!`);
        this.getArrayListByOriginDocumentHeaderId(this.saveid);
      });
    },
    // ----------- 查询的单据为：出库、销售出库、已经审核的单据 --------------
    getArrayListByOriginDocument(
      queryPath = "?pageNo=1&pageSize=5&inOutIdentification=2&inOutCategoryIdentification=4&auditMark=1"
    ) {
      queryPath += `&documentClosed=${this.searchForm.documentClosed}`;
      comHttp.getArrayListByOriginDocument(queryPath).then((res) => {
        console.log("生产材料出库单:::::", res);

        this.dataSource = [];
        const pagination = { ...this.pagination };
        pagination.total = res.result.total;
        pagination.pageSize = res.result.size;
        this.pagination = pagination;
        this.dataSource = res.result.records;
        for (let i = 0; i < res.result.records.length; i++) {
          this.dataSource[i].key = (res.result.current - 1) * 5 + i + 1;
          this.dataSource[i].documentClosed =
            res.result.records[i].documentClosed == "关闭" ? "关闭" : "开启";
        }
      });
    },

    // 获取分厂列表
    getownedBranchTree() {
      comHttp.getDepartmentList().then((res) => {
        // let tree = this.resetTree(res.result);
        console.log("获取部门树+++++++++++::::", res);
        this.ownedBranchList = res.result;
        this.changeownedBranchData(this.ownedBranchList);
      });
    },
    // 改变用友传递过来的数据为组件能识别的数据
    changeownedBranchData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.deptname;
        element["children"] = element.syncDepartmentFilesEntityList;
        element["key"] = element.pkDeptdoc;
        element["value"] = element.pkDeptdoc;

        if (element.children) {
          this.changeownedBranchData(element.children);
        }
      });
    },
    // 部门下拉框选择
    changeOwnedBranchTreeNode(key, value) {
      console.log("key", key);
      console.log("value", value);
      this.searchForm.ownedBranch_text = value[0];
      this.savefenchang = key;
    },
    // 获取单据号列表
    getOrderList() {
      let queryPath = "?string=SCCK-";
      comHttp.getOrderList(queryPath).then((res) => {
        console.log("获取销售订单列表:::::", res);
        for (let i = 0; i < res.result.length; i++) {
          this.OrderList.push(res.result[i]);
        }
      });
    },

    // 部门按钮触发
    DepartmentChange(value, options) {
      this.searchForm.deptId = options.key;
    },

    // 时间段
    getRangeTime(date, dateString) {
      this.searchForm.startTime = dateString[0];
      this.searchForm.endTime = dateString[1];
    },
    getfinishedProductDepot() {
      this.finishedProductDepotList = [];
      comHttp.getAllNumberName_new_forU8c().then((res) => {
        console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            finishedProductDepot_dictText: res.result[i].storname,
            finishedProductDepotNo: res.result[i].storcode,
            finishedProductDepot: res.result[i].pkStordoc,
          };
          this.finishedProductDepotList.push(data);
        }
      });
    },

    // 产成品仓库
    finishedProductDepotChange(value) {
      let array = value.split("|");

      // 获取物品信息列表,根据仓库编码
      // let goodsList = this.getGoodSInfo(array[0]);
      this.searchForm.finishedProductDepot = array[0];
      this.searchForm.finishedProductDepot_dictText = array[2];
      // 根据仓库查询物品信息,并存储到相应的物品信息表中

      console.log("产成品仓库仓库获取:::::", this.dataSource);
    },
    // 表单选择
    orderSelectChange(selectedRowKeys, selectedRows) {
      this.orderSelectedRowKeys = selectedRowKeys;
      this.listSelectedRowKeys = []; // 列表选择
      this.saveid = selectedRows[0].id; //保存id
      this.savedocumentClosed = selectedRows[0].documentClosed; //保存单据状态
      // 单选 拿到表单信息
      this.Form = selectedRows[0];
      console.log("this.Form33333333333", this.Form);
      this.Form[`goodsList`] = [];

      this.getArrayListByOriginDocumentHeaderId(selectedRows[0].id);
    },
    // 获取产成品分类列表
    getFinishGoodsTypeList() {
      comHttp.GetSaveCargoClassification().then((res) => {
        console.log("产成品分类列表", res);

        this.finishGoodsTypeList = res.result;
        this.changeFinishGoodsType(this.finishGoodsTypeList);
      });
    },
    // 改变用友传递过来的数据为组件能识别的数据
    changeFinishGoodsType(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.invclassname;
        element["children"] = element.syncInventoryClassificationEntityList;
        element["key"] = element.invclassname;
        element["value"] = element.pkInvcl;

        if (element.children) {
          this.changeFinishGoodsType(element.children);
        }
      });
    },

    // 处理产成品分类
    setFinishGoodsType(key, value) {
      this.searchForm.finishedProductType = key;
      this.searchForm.finishedProductType_dictText = value;
      console.log("key======>", key);
      console.log("value======>", value);
      console.log("this.forafdslfdsfdsfd", this.searchForm.finishedProductType);

      // console.log("value11111111111", key);
      // let array = target.finishGoodsType.split("|");
      // // console.log("array===", array);
      // target.finishGoodsTypeId = array[0];
      // target.finishGoodsType = array[1];
      // console.log("target.finishGoodsTypeId", target);
    },
    // 通过销售订单单号ID,查询物品信息
    getArrayListByOriginDocumentHeaderId(id) {
      comHttp
        .getArrayListByOriginId("?id=" + id + "&inOutCategoryIdentification=4")
        .then((res) => {
          console.log("物品信息::::::", res);
          this.listDataSource = res.result.list;
          this.Form.goodsList = res.result.list;

          for (let i = 0; i < this.Form.goodsList.length; i++) {
            this.Form.goodsList[i].key = i + 1;
            this.listDataSource[i].documentClosed =
              this.Form.goodsList[i].documentClosed == "关闭" ? "关闭" : "开启";
          }
        });
    },
    // 表格行选择
    listOnSelectChange(selectedRowKeys, selectedRows) {
      this.originData = [];
      console.log(selectedRowKeys, 11111111111);
      console.log(selectedRows, 222222222222);
      this.listSelectedRowKeys = selectedRowKeys;
      for (let i = 0; i < selectedRows.length; i++) {
        this.originData.push(selectedRows[i]);
        // this.originData[i].sourceNumber = this.Form.document;
      }
      this.Form.goodsList = this.originData;
      // this.originData.push(this.sourceNumber);
      console.log("originData", this.originData);
      // this.getProducePickingGoodsInfo(selectedRowKeys.id);
    },

    // ----------- 重置 ------------------
    // 对话框取消
    handleCancel() {
      this.Reset();
      this.visible = false;
    },
    // 重置
    Reset() {
      // 重置查询条件
      this.searchForm = {
        document: "",
        salesDepartment: "", // 销售部门
        deptId: "", // 销售部门Id
        rangeDate: null, // 日期范围
        documentClosed: "开启",
        startTime: "", // 开始日期
        endTime: "", // 结束日期
      };

      this.resetPagination(); // 重置分页情况
      this.getArrayListByOriginDocument(); // 重置销售订单
      this.listDataSource = []; // 重置物品数据
      // 重置选择框中选中的值
      this.listSelectedRowKeys = [];
      this.orderSelectedRowKeys = [];
    },

    // 重置当前页码及页码参数
    resetPagination() {
      this.pagination = {
        total: 0,
        current: 1,
        pageSize: 10, //每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ["10"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
      };
      //查询参数
      this.queryParam = {
        page: 1, //第几页
        size: 10, //每页中显示数据的条数
        hosName: "",
        hosCode: "",
        province: "",
        city: "",
      };
    },

    // ----------- 查询 ------------------
    // 查询
    Search() {
      let queryPath = this.getQueryPath();
      this.getArrayListByOriginDocument(queryPath);
      console.log("查询条件为:::", queryPath);
    },
    // 分页函数
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.queryParam.page = pagination.current;
      this.queryParam.size = pagination.pageSize;
      let queryPath = this.getQueryPath();
      this.getArrayListByOriginDocument(queryPath);
    },

    // 获取全局查询条件
    getQueryPath() {
      let queryPath =
        "?pageNo=" +
        this.queryParam.page +
        "&pageSize=5" +
        "&inOutIdentification=2&inOutCategoryIdentification=4&auditMark=1" +
        "&beginDate=" +
        this.searchForm.startTime +
        "&endDate=" +
        this.searchForm.endTime +
        "&document=" +
        this.searchForm.document +
        "&ownedBranch=" +
        this.savefenchang +
        "&finishedProductType=" +
        this.searchForm.finishedProductType +
        "&finishedProductDepot=" +
        this.searchForm.finishedProductDepot;
      return queryPath; // 返回的查询条件
    },

    // 打开对话框
    showModal() {
      this.visible = true;
      this.getArrayListByOriginDocument();
    },
    // 对话框提交
    handleOk() {
      console.log("this.Form==========>", this.Form);
      this.$emit("select-data", this.Form);
      this.visible = false;
      this.resetPagination(); // 重置分页
    },

    // ----------- 获取销售部门列表 --------------
    getSaleDepartmentList() {
      this.saleDepartmentList = [];
      comHttp.getSaleDepartment().then((res) => {
        console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            value: res.result[i].value,
            title: res.result[i].title,
          };
          this.saleDepartmentList.push(data);
        }
      });
    },
    //禁止选择的组件
    getCheckboxProps(record) {
      return {
        props: {
          disabled: record.documentClosed === "关闭",
        },
      };
    },
  },
};
</script>

<style></style>
